const mongodbHandler = require('../manager/mongodbManager');
const { Collection } = require('./constant');

module.exports = {
	/**
	 * 根据股票代码或股票名称来判断这支股票是否存在，如果不存在则直接返回
	 */
	validateCodeOrName: async function (codeOrName) {
		// 定义参数
		let paramForCode = {
			'code': codeOrName
		};
		let paramForName = {
			'name': codeOrName
		};
		// 表示使用股票代码作为参数，返回的结果
		let stockInfoByCodeList = [];
		// 表示使用股票名称作为参数，返回的结果
		let stockInfoByNameList = [];

		// 使用股票代码作为参数，从mongodb中查询数据
		async function getStockInfoByCode(param) {
			await mongodbHandler.findDocument(Collection.STOCK_INFO, param).then((result) => {
				if (null != result) {
					stockInfoByCodeList = result;
				}
			});
		}

		// 使用股票名称作为参数，从mongodb中查询数据
		async function getStockInfoByName(param) {
			await mongodbHandler.findDocument(Collection.STOCK_INFO, param).then((result) => {
				if (null != result) {
					stockInfoByNameList = result;
				}
			});
		}

		await getStockInfoByCode(paramForCode);
		await getStockInfoByName(paramForName);

		// stock_info集合的url_param列
		let urlParam = null;
		// stock_info集合对象
		let stockInfo = null;
		if (stockInfoByCodeList && stockInfoByCodeList.length == 1) {
			stockInfo = stockInfoByCodeList[0];
			urlParam = stockInfo.url_param;
		}
		if (stockInfoByNameList && stockInfoByNameList.length == 1) {
			stockInfo = stockInfoByNameList[0];
			urlParam = stockInfo.url_param;
		}

		// 参数有错误，没有查到这支股票，直接返回
		if (!urlParam && !stockInfo) {
			return null;
		} else {
			return { stockInfo, urlParam};
		}
	}
};